package cn.kgc.controller;

import cn.kgc.base.vo.OrderSpuInfoVo;
import cn.kgc.commons.annotation.AutoDict;
import cn.kgc.commons.annotation.MyCacheable;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.constant.PmsSpuDefaultImage;
import cn.kgc.dto.SpuInfoVO;
import cn.kgc.dto.SpuItemVO;
import cn.kgc.entity.*;
import cn.kgc.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.kgc.dto.PmsSpuInfoAddDTO;
import cn.kgc.dto.PmsSpuInfoUpdateDTO;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import cn.kgc.commons.vo.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.kgc.entity.PmsSpuInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * spu信息(PmsSpuInfo)表控制层
 *
 * @author 石浩杰
 * @since 2022-12-05 09:38:34
 */
@RestController
@RequestMapping("/pms/SpuInfo")
@Api
@Validated
public class PmsSpuInfoController {
    /**
     * 服务对象
     */
    @Resource
    private PmsSpuInfoService pmsSpuInfoService;

    @Resource
    private PmsCategoryService pmsCategoryService;

    @Resource
    private PmsBrandService pmsBrandService;

    @Resource
    private PmsSkuInfoService pmsSkuInfoService;

    @Resource
    private PmsSpuImagesService pmsSpuImagesService;

    @PostMapping("/getOrderSpuInfo")
    @ApiOperation(value = "根据spuId的集合，获得订单中商品对应的spu信息",produces = "application/charset=utf-8",httpMethod = "POST",response = Result.class)
    @CrossOrigin
    public Map<Long, OrderSpuInfoVo> getOrderSpuInfo(@RequestBody HashSet<Long> spuIdSet){
        Map<Long, OrderSpuInfoVo> map=new HashMap<>();
        //获得每个spuId
        for (Long spuId : spuIdSet) {
            //获得spu信息
            PmsSpuInfo pmsSpuInfo=pmsSpuInfoService.getById(spuId);
            //将spu的信息封装到OrderSpuInfo
            OrderSpuInfoVo orderSpuInfoVo=new OrderSpuInfoVo();
            orderSpuInfoVo.setSpuId(spuId);
            orderSpuInfoVo.setSpuName(pmsSpuInfo.getSpuName());
            orderSpuInfoVo.setCategoryId(pmsSpuInfo.getCatalogId());
            //获得品牌的数据
            PmsBrand pmsBrand=pmsBrandService.getById(pmsSpuInfo.getBrandId());
            orderSpuInfoVo.setSpuBrand(pmsBrand.getName());
            //获得商品的默认图片
            LambdaQueryWrapper<PmsSpuImages> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PmsSpuImages::getSpuId,spuId);
            lambdaQueryWrapper.eq(PmsSpuImages::getDefaultImg, PmsSpuDefaultImage.DEFAULT_IMAGE.getDefaultImage());
            PmsSpuImages pmsSpuImages=pmsSpuImagesService.getOne(lambdaQueryWrapper);
            orderSpuInfoVo.setSpuPic(pmsSpuImages.getImgUrl());
            map.put(spuId,orderSpuInfoVo);
        }
        return map;
    }

    @GetMapping("/detail/{skuId}")
    @ApiOperation(value = "查询商品详情信息",produces = "application/json;charset=utf-8",response = Result.class,httpMethod = "GET")
    @CrossOrigin
    @ApiImplicitParam(name = "skuId",value = "skuId",required = true,dataType = "Long",paramType = "path")
    @Cacheable(value="pmssspuinfo",key = "#root.method.name+#skuId",sync = true)
    public SpuItemVO detail(@PathVariable(value = "skuId") Long skuId){
        //todo 思考问题:商品信息保存到redis缓存中了，如果修改商品信息，删除缓存中数据

        PmsSkuInfo pmsSkuInfo=pmsSkuInfoService.getById(skuId);
        if (pmsSkuInfo==null){
            throw new HttpException(20008, HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        SpuItemVO spuItemVO = pmsSpuInfoService.selectById(skuId);
        return spuItemVO;
    }

    @PutMapping("/up")
    @ApiOperation(value = "上架",produces = "application/json;charset=utf-8",response = Result.class,httpMethod = "PUT")
    @CrossOrigin
    @ApiImplicitParam(name = "spuId",value = "spuId",dataType = "Long",paramType = "query")
    public boolean up(@RequestParam("spuId") Long spuId) {
        return pmsSpuInfoService.up(spuId);
    }

    /**
     * 分页查询所有数据
     *
     * @param current 分页对象
     * @return 所有数据
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询所有数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "spuName", value = "商品名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "catalogId", value = "分类id,默认值是0", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "brandId", value = "品牌id,默认值是0", paramType = "query", dataType = "int")
    })
    @CrossOrigin
    @AutoDict
    public IPage<PmsSpuInfo> selectAll(@RequestParam(defaultValue = "1") int current,
                                       @RequestParam(defaultValue = "5") int pageSize,
                                       @RequestParam(defaultValue = "") String spuName,
                                       @RequestParam(defaultValue = "0") int catalogId,
                                       @RequestParam(defaultValue = "0") int brandId) {
        LambdaQueryWrapper<PmsSpuInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(spuName), PmsSpuInfo::getSpuName, spuName);
        lambdaQueryWrapper.eq(catalogId != 0, PmsSpuInfo::getCatalogId, catalogId);
        lambdaQueryWrapper.eq(brandId != 0, PmsSpuInfo::getBrandId, brandId);

        IPage<PmsSpuInfo> page = new Page(current, pageSize);
        //查询
        pmsSpuInfoService.page(page,lambdaQueryWrapper);
        List<PmsSpuInfo> pmsSpuInfoList=page.getRecords();
        for (PmsSpuInfo pmsSpuInfo : pmsSpuInfoList) {
            long brandIdTemp=pmsSpuInfo.getBrandId();
            long catelogIdTemp=pmsSpuInfo.getCatalogId();
            PmsCategory pmsCategory=pmsCategoryService.getById(catelogIdTemp);
            if (pmsCategory!=null){
                pmsSpuInfo.setCategoryName(pmsCategory.getName());
            }
            PmsBrand pmsBrand=pmsBrandService.getById(brandIdTemp);
            if (pmsBrand!=null){
                pmsSpuInfo.setBrandName(pmsBrand.getName());
            }
        }
        return page;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @CrossOrigin
    @ApiOperation(value = "通过主键查询单条数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = Result.class)
    @ApiImplicitParam(name = "id", value = "主键", paramType = "path", dataType = "int")
    public PmsSpuInfo selectOne(@PathVariable Serializable id) {
        return this.pmsSpuInfoService.getById(id);
    }

    /**
     * 新增数据
     *
     * @param  spuInfoDTO 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    @ApiOperation(value = "新增", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = Result.class)
    @CrossOrigin
    public boolean insert(@RequestBody SpuInfoVO spuInfoDTO) {

        return pmsSpuInfoService.savePmsSpuInfo(spuInfoDTO);
    }

    /**
     * 修改数据
     *
     * @param pmsSpuInfoDTO 实体对象
     * @return 修改结果
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改信息", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = Result.class)
    @CrossOrigin
    public boolean update(@RequestBody PmsSpuInfoUpdateDTO pmsSpuInfoDTO) {
        PmsSpuInfo pmsSpuInfo = this.pmsSpuInfoService.getById(pmsSpuInfoDTO.getId());
        BeanUtils.copyProperties(pmsSpuInfoDTO, pmsSpuInfo);
        return this.pmsSpuInfoService.updateById(pmsSpuInfo);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除结果
     */
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据主键删除信息", produces = "application/json;charset=utf-8",
            httpMethod = "DELETE", response = Result.class)
    @ApiImplicitParam(name = "id", value = "主键", paramType = "path", dataType = "int")
    @CrossOrigin
    public boolean delete(@PathVariable Long id) {
        return this.pmsSpuInfoService.removeById(id);
    }
}
